package com.solvePlat.controller;

import com.solvePlat.entity.base.BaseResponse;
import com.solvePlat.entity.User;
import com.solvePlat.entity.base.LoginParam;
import com.solvePlat.service.UserService;
import com.solvePlat.shiro.ShiroKit;
import com.solvePlat.util.JWTUtil;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("getUserById")
    public User getUserById(String uuid){
        return userService.getUserById(uuid);
    }

    @RequestMapping("getUserAllInfo")
    public User getUserAllInfo(String uuid){
        return userService.getUserAllInfo(uuid);
    }


    @GetMapping("getUserIntegral")
    public User getUserIntegral(String uuid){
        return userService.getUserIntegral(uuid);
    }


    @PostMapping("/login")
    public BaseResponse<String> login (@RequestBody LoginParam loginParam){


        BaseResponse baseResponse = new BaseResponse();

        String username = loginParam.getUsername();
        String password = loginParam.getPassword();
        User user = userService.getUserByName(username);
        if (user == null){
            return new BaseResponse<>(false, "账号或者密码不正确!","" );
        }
        //随机盐
        String salt = user.getSalt();
        String encodedPassword = ShiroKit.md5(password,username+salt);
        if (encodedPassword.equals(user.getPassword())){
            String userToken = JWTUtil.sign(username, encodedPassword);
            baseResponse.setMsg("登录成功!");
            baseResponse.setSuccess(true);
            baseResponse.setData(userToken);
        }else{
            baseResponse.setMsg("登录失败!");
            baseResponse.setSuccess(false);
            baseResponse.setData("");
        }

        return baseResponse;
    }

    @PostMapping("/register")
    public BaseResponse<String> register (@RequestBody User loginParam){
        BaseResponse baseResponse = new BaseResponse();
        try{
            userService.saveUserInfo(loginParam);
            baseResponse.setSuccess(true);
            baseResponse.setMsg("注册成功!");
        }catch (Exception e){
            e.printStackTrace();
            baseResponse.setSuccess(false);
            baseResponse.setMsg(e.getMessage());
        }
        return baseResponse;
    }

}
